package com.ihelin.insurance.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ihelin.insurance.dao.AgentDao;
import com.ihelin.insurance.entity.*;
import com.ihelin.insurance.utils.SystemUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 代理人
 *
 * @author iHelin ihelin@outlook.com
 * @since 2021-02-27 16:11:38
 */
@Service
public class AgentService extends ServiceImpl<AgentDao, AgentEntity> {
    @Autowired
    private PerformanceService performanceService;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private FeedbackService feedbackService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private AnswerService answerService;

    @Transactional
    public void updateAgent(AgentEntity agentEntity) {
        PerformanceEntity performanceEntity = new PerformanceEntity();
        performanceEntity.setAgentName(agentEntity.getName());
        performanceService.update(performanceEntity, new UpdateWrapper<PerformanceEntity>().eq("agent_id", agentEntity.getId()));

        PaymentEntity paymentEntity = new PaymentEntity();
        paymentEntity.setAgentName(agentEntity.getName());
        paymentService.update(paymentEntity, new UpdateWrapper<PaymentEntity>().eq("agent_id", agentEntity.getId()));

        FeedbackEntity feedbackEntity = new FeedbackEntity();
        feedbackEntity.setAgentName(agentEntity.getName());
        feedbackService.update(feedbackEntity, new UpdateWrapper<FeedbackEntity>().eq("agent_id", agentEntity.getId()));

        AnswerEntity answerEntity = new AnswerEntity();
        answerEntity.setAgentName(agentEntity.getName());
        answerService.update(answerEntity, new UpdateWrapper<AnswerEntity>().eq("agent_id", agentEntity.getId()));

        this.updateById(agentEntity);
    }

    @Transactional
    public void deleteAgent(List<Integer> ids) {
        performanceService.remove(new QueryWrapper<PerformanceEntity>().in("agent_id", ids));
        paymentService.remove(new QueryWrapper<PaymentEntity>().in("agent_id", ids));
        feedbackService.remove(new QueryWrapper<FeedbackEntity>().in("agent_id", ids));
        customerService.remove(new QueryWrapper<CustomerEntity>().in("agent_id", ids));
        answerService.remove(new QueryWrapper<AnswerEntity>().in("agent_id", ids));
        this.removeByIds(ids);
    }

    public void calPerformance() {
        Date lastMonthDate = SystemUtil.getLastMonthDate();
        String lastMonth = SystemUtil.getLastMonth();
        QueryWrapper<AgentEntity> agentEntityQueryWrapper = new QueryWrapper<>();
        agentEntityQueryWrapper.gt("contract_period", lastMonthDate);
        List<AgentEntity> agentEntities = super.list(agentEntityQueryWrapper);
        for (AgentEntity agentEntity : agentEntities) {
            BigDecimal score = BigDecimal.ZERO;
            QueryWrapper<CustomerEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("agent_id", agentEntity.getId());
            queryWrapper.gt("end_time", lastMonthDate);
            List<CustomerEntity> customerEntities = customerService.list(queryWrapper);
            BigDecimal totalAmount = customerEntities.stream().map(CustomerEntity::getInsuranceAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            if (totalAmount.compareTo(BigDecimal.valueOf(5000L)) >= 0) {
                long countA = customerEntities.stream().filter(customerEntity -> "A".equals(customerEntity.getInsuranceType())).count();
                if (countA > 0) {
                    score = score.add(BigDecimal.valueOf(0.5).multiply(BigDecimal.valueOf(countA)));
                }
                long countB = customerEntities.stream().filter(customerEntity -> "B".equals(customerEntity.getInsuranceType())).count();
                if (countB > 0) {
                    score = score.add(BigDecimal.valueOf(0.3).multiply(BigDecimal.valueOf(countB)));
                }
                long countC = customerEntities.stream().filter(customerEntity -> "C".equals(customerEntity.getInsuranceType())).count();
                if (countC > 0) {
                    score = score.add(BigDecimal.valueOf(0.2).multiply(BigDecimal.valueOf(countC)));
                }
            }
            QueryWrapper<PerformanceEntity> performanceQueryWrapper = new QueryWrapper<>();
            performanceQueryWrapper.eq("agent_id", agentEntity.getId());
            performanceQueryWrapper.eq("time", lastMonth);
            PerformanceEntity performanceEntity = performanceService.getOne(performanceQueryWrapper);
            if (performanceEntity == null) {
                performanceEntity = new PerformanceEntity();
                performanceEntity.setAgentId(agentEntity.getId());
                performanceEntity.setAgentName(agentEntity.getName());
                performanceEntity.setTotalScore(score);
                performanceEntity.setAttendanceDays(0);
                performanceEntity.setTime(lastMonth);
                performanceService.save(performanceEntity);
            } else {
                performanceEntity.setTotalScore(score);
                performanceService.updateById(performanceEntity);
            }
        }
    }
}
